let fs = require('fs');

var nodeCrypto = require('crypto'),
    algorithm = 'aes-256-ctr',
    encrykey = buffer32('flashme.cn'); // 密钥
    // encrykey = new Uint8Array([102,108,97,115,104,109,101,46,99,110,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);

console.log('Buffer密钥：',encrykey.join(','));

function buffer32(_key) {
  // 将密钥转换为 Buffer
  var key = Buffer.from(_key, 'utf8');
  // 如果密钥长度不足 32 字节，进行填充或截断
  if (key.length !== 32) {
    key = Buffer.concat([key, Buffer.alloc(32)]).slice(0, 32);
  }
  return key;
}

function encrypt(text) {
    // 生成一个随机的初始化向量
    const iv = nodeCrypto.randomBytes(16);
    // 创建加密器
    var cipher = nodeCrypto.createCipheriv(algorithm, encrykey, iv);
    var crypted = cipher.update(text, 'utf8', 'hex');
    crypted += cipher.final('hex');
    // 将 IV 与加密数据一起返回
    return iv.toString('hex') + ':' + crypted;
}

function decrypt(text) {
  try {
    // 分离 IV 和加密数据
    const textParts = text.split(':');
    const iv = Buffer.from(textParts.shift(), 'hex');
    const encryptedText = textParts.join(':');

    // 创建解密器
    var decipher = nodeCrypto.createDecipheriv(algorithm, encrykey, iv);
    var dec = decipher.update(encryptedText, 'hex', 'utf8');
    dec += decipher.final('utf8');
    return dec;
  } catch (err) {
      return '非hex字符串';
  }
}

//解密
fs.readFile('./crypto-en.txt', 'utf8', function (err, data) {
    if (!err) {
        var dec = decrypt(data);
        console.log('解密结果：', dec);
        // fs.writeFileSync('./crypto-de.txt', dec);
    } else {
        console.log('缺失 source2.txt 加密文件');
    }
})

//加密
fs.readFile('./source.txt', 'utf8', function (err, data) {
    if (!err) {
        var enc = encrypt(data)
        console.log('加密结果：', enc);
        fs.writeFileSync('./crypto-en.txt', enc);
    } else {
        console.log('缺失 source.txt 明文文件');
    }
})
